<?php

namespace app\models;

use Yii;
use yii\db\Query;

/**
 * This is the model class for table "bf_askfor".
 *
 * @property int $id
 * @property string|null $store_name 客户名称
 * @property int|null $info_id 公司ID
 * @property string|null $legal 法人
 * @property string|null $phone 账号
 * @property string|null $type 客户类型
 * @property float|null $caigou 过去30天采购额
 * @property int|null $bf_status 状态:0发起申请，1正常，2申请冻结，3申请封禁，-1审核失败，-2已冻结，-3已封禁，-4已驳回
 * @property float|null $moneyof 审批额度
 * @property int|null $hk_mode 还款方式：1自主还款，2云途养护代付
 * @property int|null $hk_time 还款日期
 * @property string|null $reason 审核原因
 * @property string|null $remark 审核说明
 * @property string|null $created_at 申请时间
 */
class Apply
{
    public function askapply($post)
    {
        //查询是否已经申请
        $askforsql="select reason,remark,created_at From bf_askfor where store_id=".$post['id'];
        $askforres = Yii::$app->db->createCommand($askforsql)->queryOne();
        if(!empty($askforres) && empty($post['rtype'])){
            return ['code' => 401, 'message' => '请不要重复申请','data'=>$askforres];
        }else{
            $info_sql = "select a.id,a.store_name,c.legal,b.phone,c.legal,c.business_nature as type,a.infor_id From yt_trade_store a LEFT JOIN yt_user b ON b.cid = a.id LEFT JOIN yt_trade_infor c ON c.id =a.infor_id where a.id =" . $post['id'];
            $userlist = Yii::$app->db2->createCommand($info_sql)->queryOne();
            if(!empty($userlist)){
                //过去30天采购额
                $cg_sql = "select SUM(total_money) as total_money From yt_purchase_order where store_id =" . $post['id'] .
                    " AND pay_time >=" . strtotime("-1 months", time()) .
                    " AND pay_time <=" . time();
                $last_purchase = Yii::$app->db2->createCommand($cg_sql)->queryOne();
                $userlist['last_purchase'] = $last_purchase['total_money'] ? $last_purchase['total_money'] : '0.00';
                $userlist['created_at'] = time();
                $userlist['bf_status'] = 0;
                $userlist['store_id'] = $userlist['id'];
                unset($userlist['id']);
                $insert = Yii::$app->db->createCommand()->insert('bf_askfor', $userlist)->execute();
                return ['code' => 200, 'message' => 'OK', 'data' => ''];
            }else{
                return ['code' => 400, 'message' => '找不到资源','data'=>''];
            }
        }
    }



}
